package com.java2104.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//声明一个过滤器，需要实现 javax.servlet.Filter
@WebFilter(urlPatterns = {"/user1/*"}) //该过滤器将过滤以 /user/开头的URI
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.获取session对象
        HttpSession session = ((HttpServletRequest) servletRequest).getSession();
        //2.获取登录用户实例
        Object user = session.getAttribute("loginUser");
        if (user!=null) {//如果已经登录过，则user不为空
            //在请求作用域中添加一个令牌
            servletRequest.setAttribute("token", "Already login!" + System.currentTimeMillis());
            filterChain.doFilter(servletRequest, servletResponse);//请求放行
        }
        else {//user为null，说明用户还未登录
            ((HttpServletResponse) servletResponse).sendRedirect("/login");//重定向到登录页
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
